package com.gs.synedocket.adapter.base;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.gs.synedocket.control.DocketSummaryView;
import com.gs.synedocket.util.ImageUtil;

public class BaseViewHolder extends RecyclerView.ViewHolder {

    private Context context;
    private SparseArray<View> mViews;
    private View convertView;

    public BaseViewHolder(Context context, View itemView) {
        super(itemView);
        this.context = context;
        convertView = itemView;
        mViews = new SparseArray<>();
    }

    public static BaseViewHolder get(Context context, ViewGroup parent, int layoutId) {
        View itemView = LayoutInflater.from(context).inflate(layoutId, parent, false);
        return new BaseViewHolder(context, itemView);
    }

    public <T extends View> T fd(int id) {
        View view = mViews.get(id);
        if (view == null) {
            view = convertView.findViewById(id);
            mViews.put(id, view);
        }
        return (T) view;
    }

    public void setImageUrl(int id, String url, View.OnClickListener listener) {
        ImageView iv = fd(id);
        ImageUtil.loadImg(context, url, iv);
        iv.setOnClickListener(listener);
    }

    public void setImageUrl(int id, String url) {
        ImageView iv = fd(id);
        ImageUtil.loadImg(context, url, iv);
    }

    public void setImageBitmap(int id, Bitmap resource) {
        ImageView iv = fd(id);
        iv.setImageBitmap(resource);
    }

    public void setText(int id, String text) {
        TextView tv = fd(id);
        tv.setText(text);
    }

    public void setVisibility(int id, int visible) {
        View view = convertView.findViewById(id);
        view.setVisibility(visible);
    }

    public void setOnClickListener(int id, View.OnClickListener listener) {
        View view = convertView.findViewById(id);
        view.setVisibility(View.VISIBLE);
        view.setOnClickListener(listener);
    }

    public void setDocketText(int id, String text) {
        DocketSummaryView view = fd(id);
        view.setContent(text);
    }
}
